package com.alex.controller.user;

import com.alex.pojo.Book;
import com.alex.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.SessionScope;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class RoutesController {

    @Resource
    private BookService bookService;

    @RequestMapping({"/home", "/index", ""})
    public String home() {
        return "forward:/index.jsp";
    }

    @RequestMapping("/book/list")
    public String bookList(@RequestParam(value = "bn", required = false) String bn, Model model) {
        List<Book> books = null;
        System.out.println("search keyword bn: " + bn);
        if (bn == null || bn.isEmpty()) {
            books = bookService.getAll();
        } else {
            books = bookService.searchByName(bn);
        }
        model.addAttribute("books", books);
        model.addAttribute("bn", bn);
        return "list";
    }

    @RequestMapping("/book/buy")
    public String toBuy(@RequestParam("isbn") String isbn, Model model) {
        Book book = bookService.get(isbn);
        model.addAttribute("book", book);
        return "buy";
    }

    @RequestMapping("/book/doBuy")
    public String doBuy(@RequestParam("isbn") String isbn, Model model) {
        bookService.buyOneBook(isbn, "a");
        return "redirect:/book/list";
    }

}
